<?
/**
 * VoiceOne Settings/Extensions/edit
 *
 * Frontend to provide access to the extensions system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 * @todo Remove hardcoded italian message for confirmation box (AlertGood. AlertBad etc)
 */

  include ("../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
  sajax_init();

  //================ XAJAX ================
	function delCidRow($trunk_id){
    global $asterisk,$cwlang;
		// Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
		$ret=$asterisk->getTrunk($trunk_id,0);
  	if (is_array($ret)){
			$t=$ret[0];
      $trunk_name=$t["name"];
		}
    $script.=" document.getElementById('stats').deleteRow(document.getElementById('".$trunk_id."_row').rowIndex); ";
		$script.=" var optObj=document.createElement('option'); ";
		$script.=" optObj.value='".$trunk_id."'; ";
		$script.=" optObj.innerText='".$trunk_name."'; ";   //cross browser fix
    $script.=" optObj.text='".$trunk_name."'; ";        //cross browser fix
    $script.=" document.getElementById('trunklist').appendChild(optObj); ";
    $script.=" if(document.getElementById('stats').rows.length==1){ ";
    $script.="   var newRow = document.getElementById('stats').insertRow(document.getElementById('stats').rows.length); ";
    $script.="   newRow.id = 'tableintro'; ";
    $script.="   newRow.bgColor = '#ffffff'; ";
    $script.="   var newCell_01 = newRow.insertCell(0); newCell_01.colSpan = '3'; newCell_01.innerHTML = '&nbsp;'; ";
    $script.="   var newCell_234 = newRow.insertCell(1); newCell_234.colSpan = '3'; newCell_234.innerHTML = '".T_("Caller ID is set to default for all lines")."'; ";
    $script.="} ";
    // Return the xajaxResponse object
		$objResponse->addScript($script);
    return $objResponse->getXML();
  }
  function addCid($trunk_id){
    global $asterisk,$relBasePath;
		// Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
  	$ret=$asterisk->getTrunk($trunk_id,0);
  	if (is_array($ret)){
			$t=$ret[0];
      $trunk_name=$t["name"];
    	$trunk_cidnum=$t["cid_number"];
  		$trunk_cidname=$t["cid_name"];
  		$trunk_force=$t["force_cid"];
  		$truk_clir=$t["clir"];
  		$truk_numbers=$t["cid_list"];
  		if (is_array($truk_numbers))
  	  foreach ($truk_numbers as $number) $trunk_cidlist.="<option value=\"$number\">$number</option>";
		}
    if($trunk_force==1) $forceChecked="checked=\"checked\""; else $forceChecked="";
		$cell0="<img src=\"".$relBasePath."public/img/trash.gif"."\" alt=\"delTrunk\" onclick=\"xajax_delCidRow('".$trunk_id."')\" />";
		$cell1="<input type=\"checkbox\" id=\"cid[".$trunk_id."][clir]\" name=\"cid[".$trunk_id."][clir]\" />";
		$cell2="$trunk_name<input type=\"hidden\" id=\"cid[".$trunk_id."][id]\" name=\"cid[".$trunk_id."][id]\" value=\"".$trunk_id."\" /><input type=\"hidden\" id=\"cid[".$trunk_id."][name]\" name=\"cid[".$trunk_id."][name]\" value=\"".$trunk_name."\" />";
		$cell3="<select id=\"cid[".$trunk_id."][cidnum]\" name=\"cid[".$trunk_id."][cidnum]\" >".$trunk_cidlist."</select>";
		$cell4="<input type=\"text\" id=\"cid[".$trunk_id."][cidname]\" name=\"cid[".$trunk_id."][cidname]\" value=\"".$trunk_cidname."\" />";
    //$cell5="<input type=\"checkbox\" id=\"cid[".$trunk_id."][force]\" name=\"cid[".$trunk_id."][force]\" $forceChecked disabled=\"disabled\" />";
    if($forceChecked!="") $cell5="<span style=\"color: red;\"><strong>ON<strong></span>"; else $cell5="<span style=\"color: black;\">".T_("OFF")."</span>";
    // Return the xajaxResponse object
		$objResponse->addAssign($trunk_id."_row_cell0","innerHTML",$cell0);
    $objResponse->addAssign($trunk_id."_row_cell1","innerHTML",$cell1);
    $objResponse->addAssign($trunk_id."_row_cell2","innerHTML",$cell2);
    $objResponse->addAssign($trunk_id."_row_cell3","innerHTML",$cell3);
		$objResponse->addAssign($trunk_id."_row_cell4","innerHTML",$cell4);
    $objResponse->addAssign($trunk_id."_row_cell5","innerHTML",$cell5);
    $objResponse->addScript(" document.getElementById('trunklist').remove(document.getElementById('trunklist').selectedIndex); ");
    $objResponse->addScript(" document.getElementById('stats').deleteRow(document.getElementById('tableintro').rowIndex); ");
    return $objResponse->getXML();
  }
	function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_("loading")."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    $confirmBeforeSubmit="";
    //extract form params
    $client=$formData["client"];
    $id=$client["id"];
    $exten=$client["extension"];
    $alias=$client["alias"];
    $password=$client["password"];
    $confirm=$client["confirm"];
    $voicemailOn=$client["voicemailOn"];
    $vid=$client["vid"];
    $vpassword=$client["vpassword"];
    $vconfirm=$client["vconfirm"];
		if(isset($formData["cid"])) $cidArr=$formData["cid"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    //retrieve old exten and alias value
    if($id!=""){
      $ret=$asterisk->getClient($id,0);
      $v=$ret[0];
      $oldExen=$v["extension"];
      $oldAlias=$v["alias"];
    }
    // Check Extension ((no null)&&(numeric)&&(unique)&&( -neq Alias)
    $extensionErr=false;
    if($exten=="") {
      //extension cannot be null
      $errOut[]= T_("User extension cannot be null");
      $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
      $extensionErr=true;
    }else{
      //extension must be numeric
      for($i=0; $i<strlen($exten); $i++){
        $ch=ord($exten[$i]);
        if(!((($ch>47)&&($ch<58)))){
          $errOut[]= T_("User extension allow only numeric characters. Please change it");
          $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
          $extensionErr=true;
          break;
        }
      }
      //extension must be unique
      if(!(($id!="")and($exten==$oldExen))) {
        $ret=$asterisk->getExtension(0);
        if(is_array($ret)){
          foreach($ret as $e) {
            if($exten==$e["extension"]){
              $errOut[]= T_("User extension already exists. Please change it");
              $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
              $extensionErr=true;
            }
          }
        }
      }
    }
    if($extensionErr===false) $objResponse->addAssign("extensionErr","innerHTML","");
    // Check Account Password ((no null)&&(==confirm)&&(alphanumeric))
    $passwordErr=false;
    if($password==""){
      //account password cannot be not null
      $errOut[]=T_("Account password cannot be null");
      $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
      $passwordErr=true;
    }else if($password!=$confirm){
      //account password must be equal to confirm
      $errOut[]=T_("Account password and confirmation password do not match");
      $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
      $objResponse->addAssign("confirmErr","innerHTML",$imgErr);
      $passwordErr=true;
    }else{
      //account password must be alphanumeric
      for($i=0; $i<strlen($password); $i++){
        $ch=ord($password[$i]);
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58)))){
          $errOut[]=T_("Account password allows only alphanumeric characters. Please change it");
          $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
          $passwordErr=true;
          break;
        }
      }
    }
    if($passwordErr===false){
      $objResponse->addAssign("passwordErr","innerHTML","");
      $objResponse->addAssign("confirmErr","innerHTML","");
    }
    // Check Alias ((alphanumeric)&&(unique))
    $aliasErr=false;
    if($alias!=""){
      //alias must be alphanumeric
      for($i=0; $i<strlen($alias); $i++){
        $ch=ord($alias[$i]);
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58)))) {
          $errOut[]=T_("User Alias allows only alphanumeric characters. Please change it");
          $objResponse->addAssign("aliasErr","innerHTML",$imgErr);
          $aliasErr=true;
          break;
        }
      }
      //alias must be unique
      if(!(($id!="")and($alias==$oldAlias))) {
        $ret=$asterisk->getExtension(0,0);
        if(is_array($ret)){
          foreach($ret as $e){
            if($alias==$e["extension"]){
              $errOut[]=T_("User Alias already exist. Please change it");
              $objResponse->addAssign("aliasErr","innerHTML",$imgErr);
              $aliasErr=true;
              break;
            }
          }
        }
      }
      //extension must be different from Alias
      if($alias==$exten){
        $errOut[]=T_("Alias cannot match user extension. Please change it");
        $objResponse->addAssign("aliasErr","innerHTML",$imgErr);
        $aliasErr=true;
      }
    }
    if($aliasErr===false) $objResponse->addAssign("aliasErr","innerHTML","");

    // Check Voicemail Password ((==confirm)&&(numeric))
    if ($voicemailOn=="1") {
      $vpasswordErr=false;
      if($vpassword!=$vconfirm){
        //voicemail password must be equal to confirm
        $errOut[]=T_("Voicemail password and confirmation password do not match");
        $objResponse->addAssign("vpasswordErr","innerHTML",$imgErr);
        $objResponse->addAssign("vconfirmErr","innerHTML",$imgErr);
        $vpasswordErr=true;
      }else{
        //voicemail password must be numeric
        for($i=0; $i<strlen($vpassword); $i++){
          $ch=ord($vpassword[$i]);
          if(!((($ch>47)&&($ch<58)))){
            $errOut[]=T_("Voicemail password allows only numeric characters. Please change it");
            $objResponse->addAssign("vpasswordErr","innerHTML",$imgErr);
            $vpasswordErr=true;
            break;
          }
        }
      }
    }else{
      //mailbox already exists?
      if($extensionErr!==true){
      	$ret=$asterisk->getVoiceMail($exten);
      	if((is_array($ret))&&(is_array($ret[0]))&&($ret[0]["id"]!=$vid)){
        	$confirmBeforeSubmit=T_("A mailbox is alredy defined for this extension.\\nIf you continue they will be linked together.\\nAre you sure?");
      	}
      }
    }
    if($vpasswordErr===false){
      $objResponse->addAssign("vpasswordErr","innerHTML","");
      $objResponse->addAssign("vconfirmErr","innerHTML","");
    }
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      if($confirmBeforeSubmit!="") $script=" if(confirm('".$confirmBeforeSubmit."')) document.getElementById('mainform').submit(); "; else $script=" document.getElementById('mainform').submit(); ";
      $objResponse->addScript($script);
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }

  $xajax = new xajax();
	$xajax->registerFunction("addCid");
	$xajax->registerFunction("delCidRow");
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  //================== POST ====================

  if(count($_POST)>0){
    $group=$_POST["group"];
    $technology=$_POST["technology"];
    $entry=Array(
          "id" => $client["id"],
          "name" => $client["name"],
          "surname" => $client["surname"],
          "extension" => $client["extension"],
          "alias" => $client["alias"],
        //"username" => $client["username"],
          "password" => $client["password"],
          "language" => $client["language"],
          "groups" => $group,
          "technology" => $technology
        );
    //add options to the entry
    foreach ($_POST as $k=>$v) {
      if (substr($k,0,7)=="status_") {
        $k=substr($k,7);
        if ($v=="1") {
          $o["key"]=$k;
          $o["value"]=$_POST["option_".$k];
          $options[]=$o;
        }
      }
    }
    $entry["options"]=$options;
    //set voicemail
    if ($client["voicemailOn"]=="1") {
      $mailbox["mailbox"]=$client["extension"];
      $mailbox["password"]=$client["vpassword"];
      $mailbox["fullname"]=$client["name"]." ".$client["surname"];
      $mailbox["email"]=$client["email"];
      $mailbox["attach"]=$client["attach"];
      $mailbox["saycid"]=$client["saycid"];
      $mailbox["hidefromdir"]=$client["hidefromdir"];
      $entry["voicemail"]=$mailbox;
    }else{
      //if mailbox already exists link extension to mailbox
      $ret=$asterisk->getVoiceMail($client["extension"]);
      if((is_array($ret))&&(is_array($ret[0]))&&($ret[0]["id"]!=$client["vid"])){
        $mailbox["mailbox"]=$client["extension"];
        $mailbox["password"]=$ret[0]["password"];
        $mailbox["fullname"]=$client["name"]." ".$client["surname"];
        $mailbox["email"]=$ret[0]["email"];
        $mailbox["attach"]=$ret[0]["attach"];
        $mailbox["saycid"]=$ret[0]["saycid"];
        $mailbox["hidefromdir"]=$ret[0]["hidefromdir"];
        $entry["voicemail"]=$mailbox;
      }
    }
    //put Client
    $ret=$asterisk->putClient($entry);
    if ($ret>0) {
		$putted=true;
      $alert="<div class=\"AlertGood\">".T_("Extension successfully saved")."</div>";
      $_GET["id"]=$ret;
    }else{
		  $alert="<div class=\"AlertBad\">".T_("Edit failed")."</div>";
		  $putted=false;
	  }
	  //put Cid
    $extension_id=0;
    unset($entry);
    $entry=array();
    if(isset($_POST["cid"])) $cidArr=$_POST["cid"];
    if($putted===true){
      $ret=$asterisk->gelClientFromExtension($client["extension"]);
      if(is_array($ret)) $extension_id=$ret["id"];
      if(is_array($cidArr)){
        if($extension_id!=0){
    		  foreach($cidArr as $t){
    			  $cid["id"]=0;
    				$cid["trunk"]=$t["id"];
    				$cid["extension"]=$extension_id;
    				if(isset($t["clir"])&&($t["clir"]=="on")){
    				  $cid["clir"]=1;
    				  $cid["cid_number"]=$t["cidnum"];
    				  $cid["cid_name"]=$t["cidname"];
    				}else{
    				  $cid["clir"]=0;
    					$cid["cid_number"]=$t["cidnum"];
    					$cid["cid_name"]=$t["cidname"];
    				}
    				$entry[]=$cid;
    			}
          $ret=$asterisk->putCid($extension_id,$entry);
          if ($ret<1) $alert="<div class=\"AlertGood\">".T_("Error posting cid options (Extension successfully saved)")."</div>";
        }
      }else{
        $ret=$asterisk->delCid(0,$extension_id);
        if ($ret<1) $alert="<div class=\"AlertGood\">".T_("Error posting cid options (Extension successfully saved)")."</div>";
      }
    }
    //go to main page
    goToMainPage($alert,"../");
  }

  //================ PAGE LOGIC ================
  //Get the client informations
  if (isset($_GET["id"]) and $_GET["id"]!="") {
    $id=$_GET["id"];
    $ret=$asterisk->getClient($id,0);
    if ($err=$asterisk->getError()) die("Error: $err");
    $v=$ret[0];
    $id=$v["id"];
    $name=$v["name"];
    $surname=$v["surname"];
    $extension=$v["extension"];
    $alias=$v["alias"];
    $username=$v["username"];
    $password=$v["password"];
    $language=$v["language"];
    $rule=$v["rule"];
    $technology=$v["technology"];
    $optionsArr=$v["options"];
    $groupsArr=$v["groups"];
    $voicemailArr=$v["voicemail"];
    //tech icon
    if ($technology==SIP) $prot="<img src=\"$relBasePath/public/img/sip.gif\" alt=\"sip\" />";
    if ($technology==IAX2) $prot="<img src=\"$relBasePath/public/img/iax.gif\" alt=\"iax\" />";
    //read the mailbox
    if (count($voicemailArr)>0) {
      $voicemailOn="1";
      error_log("ID: ".$vid);
      $vid=$voicemailArr["id"];
      $vpassword=$voicemailArr["password"];
      $email=$voicemailArr["email"];
      $attach=$voicemailArr["attach"];
      $saycid=$voicemailArr["saycid"];
      $hidefromdir=$voicemailArr["hidefromdir"];
    } else $voicemailOn="0";
		//load cid
    $cidArr=$asterisk->getCid(0,$id);
  	if(is_array($cidArr))
    foreach ($cidArr as $c) {
      $trunk_id=$c["trunk"];
			$clir=$c["clir"];
			$cidnum=$c["cid_number"];
			$cidname=$c["cid_name"];
			$trunkArr=$asterisk->getTrunk($trunk_id,0);
      if(is_array($trunkArr)){
        $t=$trunkArr[0];
        $trunk_name=$t["name"];
    		$truk_numbers=$t["cid_list"];
        $trunk_force=$t["force_cid"];
        $numberslist="";
    		if (is_array($truk_numbers))
    	  foreach ($truk_numbers as $number){
          if($cidnum==$number) $numberslist.="<option value=\"$number\" selected=\"selected\">$number</option>";
          else $numberslist.="<option value=\"$number\">$number</option>";
        }
  		}
      if($trunk_force==1) $forceChecked="checked=\"checked\""; else $forceChecked="";
      if($clir==1) $checked="checked=\"checked\""; else $checked="";
  		$cidlist.="<tr id=\"".$trunk_id."_row\" bgcolor=\"#ffffff\">";
    	$cidlist.="<td><img src=\"".$relBasePath."public/img/trash.gif"."\" alt=\"delTrunk\" onclick=\"xajax_delCidRow('".$trunk_id."')\" /></td>";
    	$cidlist.="<td><input type=\"checkbox\" id=\"cid[".$trunk_id."][clir]\" name=\"cid[".$trunk_id."][clir]\" $checked /></td>";
    	$cidlist.="<td>$trunk_name<input type=\"hidden\" id=\"cid[".$trunk_id."][id]\" name=\"cid[".$trunk_id."][id]\" value=\"".$trunk_id."\" /><input type=\"hidden\" id=\"cid[".$trunk_id."][name]\" name=\"cid[".$trunk_id."][name]\" value=\"".$cidname."\" /></td>";
      $cidlist.="<td><select id=\"cid[".$trunk_id."][cidnum]\" name=\"cid[".$trunk_id."][cidnum]\">".$numberslist."</select></td>";
    	$cidlist.="<td><input type=\"text\" id=\"cid[".$trunk_id."][cidname]\" name=\"cid[".$trunk_id."][cidname]\" value=\"".$cidname."\"/></td>";
      if($forceChecked!="") $cidlist.="<td><span style=\"color: red;\"><strong>ON<strong></span></td>"; else $cidlist.="<td><span style=\"color: black;\">".T_("OFF")."</span></td>";
    	$cidlist.="</tr>\n";
			$trunksOnCid[]=$trunk_id;
    }
    if(!(is_array($trunksOnCid))) $cidlist="<tr id=\"tableintro\" bgcolor=\"#ffffff\"><td colspan=\"3\"></td><td colspan=\"3\">".T_("Caller ID is set to default for all lines")."</td></tr>";
		//create trunk list
  	$ret=$asterisk->getTrunk(0,0);
  	if (is_array($ret))
    foreach ($ret as $t) {
      $trunk_id=$t["id"];
      $trunk_name=$t["name"];
      $trunk_enable=$t["enable_cid"];
      if($trunk_enable==1){
  			if(is_array($trunksOnCid)){
          if (!(in_array($trunk_id,$trunksOnCid))) $trunklist.="<option id=\"".$trunk_id."_opt\" value=\"$trunk_id\">$trunk_name</option>";
        }
        else $trunklist.="<option id=\"".$trunk_id."_opt\" value=\"$trunk_id\">$trunk_name</option>";
      }
		}
    //title
    $title=sprintf(T_("Account: %1\$s &lt;%2\$s %3\$s&gt;"),$extension ,$surname, $name );
  }
  else{
	  //load cid
	  $cidlist="<tr id=\"tableintro\" bgcolor=\"#ffffff\"><td colspan=\"3\"></td><td colspan=\"3\">".T_("Caller ID is set to default for all lines")."</td></tr>";
	  //create trunk list
  	$ret=$asterisk->getTrunk(0,0);
  	if (is_array($ret))
    foreach ($ret as $t) {
      $trunk_id=$t["id"];
      $trunk_name=$t["name"];
      $trunk_enable=$t["enable_cid"];
      if($trunk_enable==1) $trunklist.="<option id=\"".$trunk_id."_opt\" value=\"$trunk_id\">$trunk_name</option>";
    }
    //title
    $title=T_("New Extension");
    unset($v);
  }
  //create the language list
  $availLang=getAvailLang();
  foreach($availLang as $l) {
    if ($l==$language or (!isset($language) and $l==$cwLanguage)) $s="selected=\"selected\""; else $s="";
    $langSelect.="<option value=\"$l\" $s>$l</option>\n";
  }
  //prepare the sidebar
  $retBuddy=$asterisk->getClient(0,0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($retBuddy))
  foreach ($retBuddy as $vBuddy) {
    $buddyid=$vBuddy["id"];
    $buddyExt=$vBuddy["extension"];
    $buddyName=$vBuddy["name"];
    $buddySurname=$vBuddy["surname"];
    $buddiesList.="<tr><td class=\"postit\"><a href=\"./?id=$buddyid\" >$buddyExt</a></td><td><a href=\"./?id=$buddyid\">$buddyName $buddySurname</a></td></tr>\n";
  }
	/**
   * IS EXTNENSION CONTAINED IN A VIRTUAL EXTENSION?
   * If extension is contained in a Virtual Extension it means that:
   *  - no voicemail is associated to extension (user can enable/disable virtual extension's voicemail)
   *  - cid settings are managable on the relative virtual extension's page
   *  - groups are managable on the relative virtual extension's page 
   */
  $isPartOfVirtualExension=false;
  $disabledContext=0;
  if(isset($_GET["id"])&&($_GET["id"]!="")){
  	$virtual=getVirtualExtensionFromClient($_GET["id"]);
  	if(is_array($virtual)){
    	$isPartOfVirtualExension=true;
      $disabledContext=1;
    }
  }
  
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/"); ?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3><a href="../" class="admin" ><?=T_("Return without save")?></a></h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>" method="post">
      <table>
        <tr>
          <td>
            <p class="blockintro"><?=T_("Personal information")?></p>
            <div class="block">
              <dl>
                <dt class="required"><label for="client[name]"><?=T_("Name")?>:</label></dt>
                <dd><input type="text" size="25" maxlength="30" id="client[name]" name="client[name]" value="<?=$name?>" /><span id="nameErr"></span></dd>
                <dt class="required"><label for="client[surname]"><?=T_("Surname")?>:</label></dt>
                <dd><input type="text" size="25" maxlength="50" id="client[surname]" name="client[surname]" value="<?=$surname?>" /><span id="surnameErr"></span></dd>
                <dt class="required"><label for="client[extension]"><?=T_("Extension")?>:</label></dt>
                <dd><input type="text" size="25" maxlength="20" id="client[extension]" name="client[extension]" value="<?=$extension?>" onkeyup="document.getElementById('client[username]').value=this.value;"  onblur="document.getElementById('client[username]').value=this.value;" /><span id="extensionErr"></span></dd>
                <dt class="required"><label for="client[alias]"><?=T_('Alias')?>:</label></dt>
                <dd><input type="text" size="25" maxlength="100" id="client[alias]" name="client[alias]" value="<?=$alias?>" /><span id="aliasErr"></span></dd>
              </dl>
            </div>
          </td>
          <td>
            <p class="blockintro"><?=T_("Account Information")?></p>
            <div class="block">
              <dl>
                <dt class="required"><label for="client[username]"><?=T_("Username")?>:</label></dt>
                <dd><input type="text" size="25" maxlength="20" id="client[username]" name="client[username]" value="<?=$extension?>" disabled="disabled" /><span id="usernameErr"></span></dd>
                <dt class="required"><label for="client[password]"><?=T_("Password")?>:</label></dt>
                <dd><input type="password" size="25" maxlength="20" id="client[password]" name="client[password]" value="<?=$password?>" /><span id="passwordErr"></span></dd>
                <dt class="required"><label for="client[confirm]"><?=T_("Confirm")?>:</label></dt>
                <dd><input type="password" size="25" maxlength="20" id="client[confirm]" name="client[confirm]" value="<?=$password?>" /><span id="confirmErr"></span></dd>
              	<dt class="required"><label for="client[language]"><?=T_('Language')?>:</label></dt>
                <dd><select id="client[language]" name="client[language]"><?=$langSelect?></select></dd>
              </dl>
            </div>
          </td>
        </tr>
      </table>
      
			<? echo listOption($js, $technology, $optionsArr, false, true, RULE_OUTGOING, true, false, $disabledContext);?>      
      
<? if($isPartOfVirtualExension===false){ ?>  

      <h2><?=T_('VoiceMail')?></h2>
      <p class="blockintro"><?=T_('Insert here the voicemail information')?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="client[voicemailOn]"><?=T_("Active")?>:</label></dt>
          <dd>
            <input type="hidden" id="client[vid]" name="client[vid]" value="<?=$vid?>" />
            <input type="radio" id="client[voicemailOn]" name="client[voicemailOn]" value="1" <?if ($voicemailOn==1) echo "checked=\"checked\""; ?> /> <?=T_("ON")?>
            <input type="radio" id="client[voicemailOn]" name="client[voicemailOn]" value="0" <?if ($voicemailOn!=1) echo "checked=\"checked\""; ?> /> <?=T_("OFF")?>
          </dd>
          <dt class="required"><label for="client[email]"><?=T_("Email")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="100" id="client[email]" name="client[email]" value="<?=$email?>" /> <?=T_("Email address (leave blank for no notification)")?></dd>
          <dt class="required"><label for="client[vpassword]"><?=T_("Password")?>:</label></dt>
          <dd><input type="password" size="25" maxlength="20" id="client[vpassword]" name="client[vpassword]" value="<?=$vpassword?>" /><span id="vpasswordErr"></span> <?=T_("Set the password to hear voicemail")?></dd>
          <dt class="required"><label for="client[vconfirm]"><?=T_("Confirm")?>:</label></dt>
          <dd><input type="password" size="25" maxlength="20" id="client[vconfirm]" name="client[vconfirm]" value="<?=$vpassword?>" /><span id="vconfirmErr"></span> <?=T_("Confirm the password to hear voicemail")?></dd>
          <dt class="required"><label for="client[attach]"><?=T_("Attach")?>:</label></dt>
          <dd><input type="checkbox" id="client[attach]" name="client[attach]" value="1" <?if ($attach==1) echo "checked=\"checked\""; ?> />
          <?=T_("If enabled, the audio message will be sent as attachment to your email")?> </dd>
          <dt class="required"><label for="client[saycid]"><?=T_("Say CID")?>:</label></dt>
          <dd><input type="checkbox" id="client[saycid]" name="client[saycid]" value="1" <?if ($saycid==1) echo "checked=\"checked\""; ?> />
          <?=T_("If enabled, the Caller ID will be included")?></dd>
          <dt class="required"><label for="client[hidefromdir]"><?=T_("Hide")?>:</label></dt>
          <dd><input type="checkbox" id="client[hidefromdir]" name="client[hidefromdir]" value="1"  <?if ($hidefromdir==1) echo "checked=\"checked\""; ?> />
          <?=T_("If enabled, you will be hidden from the directory")?></dd>
        </dl>
      </div>
		
    
			<h2><?=T_("Caller ID")?></h2>
      <p class="blockintro"><?=T_("Set CID on outgoing lines")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="trunklist"><?=T_("Line")?>:</label></dt>
          <dd><select id="trunklist" name="trunklist"><?=$trunklist?></select><span> <img src="<?=$relBasePath?>/public/img/add.gif" alt="addCid" onclick=" addCidRow(); "/>&nbsp;<?=T_("add personal Caller ID for selected line")?></span></dd>
        </dl>
				<table  id="stats" cellpadding="0" cellspacing="0">
				  <tr><th></th><th><?=T_("CLIR")?></th><th><?=T_("Line")?></th><th><?=T_("CID Number")?></th><th><?=T_("CID Name")?></th><th><?=T_("Line Overwrite")?></th></tr>
				  <span id="intable"><?=$cidlist?></span>
				</table>
      </div>   
     
		<? echo listGroup(GROUP_OF_EXTENSION, $js, $groupsArr);?>              

<? } ?>     

    <div class="action">
      <?if ($_GET["id"]!="") {?> <input type="hidden" id="client[id]" name="client[id]" value="<?=$id?>" /><?}?>
      <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="javascript:history.back(); return false;"/></a> <!-- onclick=" location.href='../'; return false;" -->
      <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
   <!--
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="return checkParam(document.getElementById('client[extension]').value, document.getElementById('client[alias]').value, document.getElementById('client[password]').value, document.getElementById('client[confirm]').value);"/>
    -->
    </div>
  </form>
 </div>

  <script>
    function addCidRow(){
      document.getElementById('alert').innerHTML='';
      var newRowIndex = (document.getElementById('stats').rows.length);
      var newRow = document.getElementById('stats').insertRow(newRowIndex);
      newRow.id = document.getElementById('trunklist').options[document.getElementById('trunklist').selectedIndex].value + "_row";
      newRow.bgColor = "#ffffff";
      var newCell_0 = newRow.insertCell(0); newCell_0.id = newRow.id + "_cell0";
      var newCell_1 = newRow.insertCell(1); newCell_1.id = newRow.id + "_cell1";
      var newCell_2 = newRow.insertCell(2); newCell_2.id = newRow.id + "_cell2";
      var newCell_3 = newRow.insertCell(3); newCell_3.id = newRow.id + "_cell3";
      var newCell_4 = newRow.insertCell(4); newCell_4.id = newRow.id + "_cell4";
      var newCell_5 = newRow.insertCell(5); newCell_5.id = newRow.id + "_cell5";
      xajax_addCid(document.getElementById('trunklist').options[document.getElementById('trunklist').selectedIndex].value);
    }
  </script>

  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="extensions";include("../../sidebar.php");?>
      <h1><?=T_("Other Extensions")?></h1>
      <p><?=T_("You can watch the other extension by click on them:")?></p>
      <table class="small">
        <?=$buddiesList?>
      </table>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
  sajax_handle_client_request();
  $smarty->assign("section", "extensions");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>

